import { getCurrentInstance, reactive } from "vue"
import { ElMessage } from "element-plus"
import { useRouter } from "vue-router"
export const useLogin = () => {
  const { $http } = getCurrentInstance().appContext.config.globalProperties
  const router = useRouter()
  const ruleForm = reactive({
    username: "",
    password: "",
  })
  function login() {
    $http.post("/api/login", ruleForm).then(res => {
      if (res.status) {
        localStorage.setItem("token", `Bearer ${res.token}`)
        localStorage.setItem("userinfo", JSON.stringify(res.userinfo))
        router.push("/home")
        ElMessage({
          message: res.msg,
          type: "success",
        })
      } else {
        ElMessage({
          message: "用户名或密码错误",
          type: "warning",
        })
      }
    })
  }
  
  return { ruleForm, login }
}
